package com.example.mymusicdisplay.view;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.view.OnApplyWindowInsetsListener;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.example.mymusicdisplay.MusicManager;
import com.example.mymusicdisplay.R;
import com.example.mymusicdisplay.data.MusicData;
import com.example.mymusicdisplay.databinding.FragmentLocalMusicBinding;
import com.example.mymusicdisplay.utils.LiveDataBus;
import com.example.mymusicdisplay.utils.MediaPlayerUtil;
import com.example.mymusicdisplay.utils.MusicUtils;
import com.example.mymusicdisplay.view.adapter.LocalMusicAdapter;
import com.example.mymusicdisplay.viewmodel.MusicViewModel;

import java.util.List;

public class LocalMusicFragment extends Fragment {

    private FragmentLocalMusicBinding mLocalMusicBinding;
    private static final String TAG = "LocalMusicFragment";

    private List<MusicData> mMusicList;
    private NavController mNavController;
    private LocalMusicAdapter mAdapter;
    private MusicViewModel mMusicViewModel;

    public static String NOTIFICATION_ACTION = "notification_action";
    public static String NOTIFICATION_BTN_STATE = "notification_btn_state";
    public static final int NOTIFICATION_PLAY = 0,
        NOTIFICATION_NEXT_MUSIC = 1,
        NOTIFICATION_PRE_MUSIC = 2;


    public LocalMusicFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBroadcastReceiver();
    }

    private void initBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(NOTIFICATION_ACTION);
        requireContext().registerReceiver(mReceiver, intentFilter);
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive: BroadcastReceiver");
            if (intent.getAction().equals(NOTIFICATION_ACTION)) {
                switch (intent.getIntExtra(NOTIFICATION_BTN_STATE, -1)) {
                    case NOTIFICATION_PRE_MUSIC:
                        MusicManager.getInstance().beforeMusic();
                        break;
                    case NOTIFICATION_PLAY:
                        if (MediaPlayerUtil.getInstance().isPlaying()) {
                            MusicManager.getInstance().pauseMusic();
                        } else {
                            MusicManager.getInstance().playMusic();
                        }
                        break;
                    case NOTIFICATION_NEXT_MUSIC:
                        MusicManager.getInstance().nextMusic();
                        break;
                    default:
                        break;
                }
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mLocalMusicBinding = DataBindingUtil
            .inflate(LayoutInflater.from(requireContext()),
                R.layout.fragment_local_music, container, false);
        mMusicViewModel = new ViewModelProvider(
            requireActivity(), new ViewModelProvider.NewInstanceFactory()).get(MusicViewModel.class);
        mLocalMusicBinding.setViewModel(mMusicViewModel);
        mLocalMusicBinding.setLifecycleOwner(requireActivity());
        ViewCompat.setOnApplyWindowInsetsListener(mLocalMusicBinding.localTitle, new OnApplyWindowInsetsListener() {
            @Override
            public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) v.getLayoutParams();
                layoutParams.topMargin = insets.getSystemWindowInsetTop();
                return insets;
            }
        });
        return mLocalMusicBinding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
        initObserver();
        initClickListener();
    }

    private void initObserver() {
        mMusicViewModel.getCurrentMusic().observe(getViewLifecycleOwner(), new Observer<MusicData>() {
            @Override
            public void onChanged(MusicData musicData) {
                Bitmap musicCover = MusicUtils.getArtwork(requireContext(),
                    musicData.getSingId(),
                    musicData.getAlbumId(), true, false);
                musicData.setLocalCover(musicCover);
                Glide.with(requireActivity())
                    .load(musicCover)
                    .into(mLocalMusicBinding.localMusicCover);
            }
        });
    }

    private void initData() {
        Bundle bundle = getArguments();
        mMusicList = (List<MusicData>) bundle.get("musicList");
        Log.d(TAG, "onActivityCreated: musicList = " + mMusicList);

        mAdapter = new LocalMusicAdapter(requireContext(), getViewLifecycleOwner());
        mAdapter.setMusicDataList(mMusicList);
        MusicManager.getInstance().initMusicList(mMusicList);
        //防止刷新紊乱
        mAdapter.setHasStableIds(true);

        mLocalMusicBinding.localMusicRecycler
            .setLayoutManager(new LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false));
        mLocalMusicBinding.localMusicRecycler.setAdapter(mAdapter);
        mNavController = Navigation.findNavController(mLocalMusicBinding.getRoot());
    }

    private void initClickListener() {

        mLocalMusicBinding.localBack.setOnClickListener(view -> {
            mNavController.navigateUp();
        });

        mLocalMusicBinding.localPlay.setOnClickListener(view -> {
            mNavController.navigate(R.id.action_localMusicFragment_to_playingMusicFragment);
        });

        mLocalMusicBinding.playOrStop.setOnClickListener(view -> {
            if (MediaPlayerUtil.getInstance().isPlaying()) {
                MusicManager.getInstance().pauseMusic();
            } else {
                MusicManager.getInstance().playMusic();
            }
        });
    }
}